package com.hotelManager.www.service;

import com.hotelManager.www.dao.UserDao;
import com.hotelManager.www.dao.ShopDao;
import com.hotelManager.www.dao.MerchantUserBlacklistDao;
import com.hotelManager.www.po.ShopBlacklist;
import com.hotelManager.www.po.Shop;
import com.hotelManager.www.po.UserBlacklist;
import com.hotelManager.www.util.JDBCUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class BlacklistService {
    private UserDao userDao;
    private ShopDao shopDao;
    private final MerchantUserBlacklistDao userBlacklistDao;
    private final Connection conn;

    public BlacklistService() {
        this.userDao = new UserDao();
        this.shopDao = new ShopDao();
        this.userBlacklistDao = new MerchantUserBlacklistDao();
        try {
            this.conn = JDBCUtils.getConnection();
        } catch (Exception e) {
            throw new RuntimeException("数据库连接初始化失败", e);
        }
    }

    // 添加商家到黑名单
    public boolean addToBlacklist(int userId, int shopId) throws Exception {
        Connection conn = null;
        try {
            System.out.println("开始拉黑商家，用户ID: " + userId + ", 商家ID: " + shopId);
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);
            System.out.println("数据库连接成功，事务已开启");

            // 检查商家是否存在
            Shop shop = shopDao.findById(shopId);
            if (shop == null) {
                System.out.println("商家不存在，商家ID: " + shopId);
                throw new IllegalArgumentException("商家不存在");
            }
            System.out.println("商家存在，商家ID: " + shopId);

            // 检查是否已经在黑名单中
            if (userDao.isShopBlacklisted(conn, userId, shopId)) {
                System.out.println("商家已在黑名单中，用户ID: " + userId + ", 商家ID: " + shopId);
                throw new IllegalStateException("该商家已在黑名单中");
            }
            System.out.println("商家未在黑名单中，继续添加");

            // 添加到黑名单
            boolean success = userDao.addToBlacklist(conn, userId, shopId);
            System.out.println("添加到黑名单结果: " + success);


            if (success) {
                // 检查是否存在状态为confirmed的订单
                String checkSql = "SELECT COUNT(*) FROM orders WHERE user_id = ? AND shop_id = ? AND status = 'confirmed'";
                try (PreparedStatement checkPs = conn.prepareStatement(checkSql)) {
                    checkPs.setInt(1, userId);
                    checkPs.setInt(2, shopId);
                    try (ResultSet rs = checkPs.executeQuery()) {
                        if (rs.next() && rs.getInt(1) > 0) {
                            // 自动退款已确认的订单
                            System.out.println("开始自动退款已确认的订单");
                            refundConfirmedOrders(userId, shopId, conn);
                            System.out.println("自动退款完成");
                        } else {
                            System.out.println("没有状态为confirmed的订单，无需退款");
                        }
                    }
                }
            }

            conn.commit();
            System.out.println("事务提交成功");
            return success;
        } catch (SQLException e) {
            if (conn != null) {
                System.out.println("发生异常，事务回滚");
                conn.rollback();
            }
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                conn.setAutoCommit(true);
                conn.close();
                System.out.println("数据库连接已关闭");
            }
        }
    }

    // 从黑名单中移除商家
    public boolean removeFromBlacklist(int userId, int shopId) throws Exception {
        try (Connection conn = JDBCUtils.getConnection()) {
            return userDao.removeFromBlacklist(conn, userId, shopId);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取用户的黑名单列表
    public List<Shop> getUserBlacklist(int userId) throws Exception {
        try (Connection conn = JDBCUtils.getConnection()) {
            return userDao.getUserBlacklist(conn, userId);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 检查商家是否在黑名单中
    public boolean isShopBlacklisted(int userId, int shopId) throws Exception {
        try (Connection conn = JDBCUtils.getConnection()) {
            return userDao.isShopBlacklisted(conn, userId, shopId);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取所有未被拉黑的商家
    public List<Shop> getAllShopsExceptBlacklisted(int userId) throws Exception {
        try (Connection conn = JDBCUtils.getConnection()) {
            return shopDao.getAllShopsExceptBlacklisted(conn, userId);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 搜索未被拉黑的商家
    public List<Shop> searchShopsExceptBlacklisted(int userId, String keyword,
                                                   String location, BigDecimal minPrice, BigDecimal maxPrice) throws Exception {
        try (Connection conn = JDBCUtils.getConnection()) {
            return shopDao.searchShopsExceptBlacklisted(conn, userId, keyword,
                    location, minPrice, maxPrice);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 获取单个未被拉黑的商家详情
    public Shop getShopByIdExceptBlacklisted(int userId, int shopId) throws Exception {
        try (Connection conn = JDBCUtils.getConnection()) {
            return shopDao.getShopByIdExceptBlacklisted(conn, userId, shopId);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 添加用户到黑名单
    public boolean addUserToBlacklist(Integer shopId, Integer userId) throws Exception {
        Connection conn = null;
        try {
            conn = JDBCUtils.getConnection();
            conn.setAutoCommit(false);
            
            UserBlacklist userBlacklist = new UserBlacklist();
            userBlacklist.setShopId(shopId);
            userBlacklist.setUserId(userId);
            userBlacklist.setCreatedAt(new Timestamp(System.currentTimeMillis()));
            
            boolean success = userBlacklistDao.addToBlacklist(conn, userBlacklist);
            
            if (success) {
                // 自动取消未完成的订单
                cancelUnfinishedOrders(userId, shopId, conn);
            }
            
            conn.commit();
            return success;
        } catch (SQLException e) {
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
            return false;
        } finally {
            if (conn != null) {
                try {
                    conn.setAutoCommit(true);
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 获取商家的黑名单列表
    public List<UserBlacklist> getBlacklistByShopId(Integer shopId) {
        return userBlacklistDao.getBlacklistByShopId(conn, shopId);
    }

    // 从黑名单中移除用户
    public boolean removeUserFromBlacklist(Integer id) {
        return userBlacklistDao.removeUserFromBlacklist(conn, id);
    }
    
    // 检查用户是否在商家的黑名单中
    public boolean isUserBlacklisted(Integer shopId, Integer userId) throws Exception {
        try (Connection conn = JDBCUtils.getConnection()) {
            return userBlacklistDao.isUserBlacklisted(conn, shopId, userId);
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
    
    // 自动退款已确认的订单
    private void refundConfirmedOrders(int userId, int shopId, Connection conn) throws SQLException {
        // 获取用户的所有已确认订单
        String sql = "SELECT * FROM orders WHERE user_id = ? AND shop_id = ? AND status = 'confirmed'";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, userId);
            ps.setInt(2, shopId);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    int orderId = rs.getInt("id");
                    BigDecimal amount = rs.getBigDecimal("total_amount");
                    
                    // 更新订单状态为已取消
                    String updateOrderSql = "UPDATE orders SET status = 'refund' WHERE id = ?";
                    try (PreparedStatement updatePs = conn.prepareStatement(updateOrderSql)) {
                        updatePs.setInt(1, orderId);
                        updatePs.executeUpdate();
                    }
                    
                    // 退还用户余额
                    String updateBalanceSql = "UPDATE users SET balance = balance + ? WHERE id = ?";
                    try (PreparedStatement balancePs = conn.prepareStatement(updateBalanceSql)) {
                        balancePs.setBigDecimal(1, amount);
                        balancePs.setInt(2, userId);
                        balancePs.executeUpdate();
                    }
                    
                    // 恢复房间状态为可用
                    String roomCode = rs.getString("uni_room_code");
                    if (roomCode != null && !roomCode.isEmpty()) {
                        String updateRoomSql = "UPDATE room SET status = 'available' WHERE room_code = ?";
                        try (PreparedStatement roomPs = conn.prepareStatement(updateRoomSql)) {
                            roomPs.setString(1, roomCode);
                            roomPs.executeUpdate();
                        }
                    }
                }
            }
        }
    }
    
    // 自动取消未完成的订单
    private void cancelUnfinishedOrders(int userId, int shopId, Connection conn) throws SQLException {
        // 获取商家的所有未完成订单
        String sql = "SELECT * FROM orders WHERE shop_id = ? AND user_id = ? AND status IN ('pending', 'confirmed')";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            ps.setInt(1, shopId);
            ps.setInt(2, userId);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    int orderId = rs.getInt("id");
                    String status = rs.getString("status");
                    BigDecimal amount = rs.getBigDecimal("total_amount");
                    
                    // 更新订单状态为已取消
                    String updateOrderSql = "UPDATE orders SET status = 'cancelled' WHERE id = ?";
                    try (PreparedStatement updatePs = conn.prepareStatement(updateOrderSql)) {
                        updatePs.setInt(1, orderId);
                        updatePs.executeUpdate();
                    }
                    
                    // 如果是已确认订单，退还用户余额
                    if ("confirmed".equals(status)) {
                        String updateBalanceSql = "UPDATE users SET balance = balance + ? WHERE id = ?";
                        try (PreparedStatement balancePs = conn.prepareStatement(updateBalanceSql)) {
                            balancePs.setBigDecimal(1, amount);
                            balancePs.setInt(2, userId);
                            balancePs.executeUpdate();
                        }
                    }
                    
                    // 恢复房间状态为可用
                    String roomCode = rs.getString("uni_room_code");
                    if (roomCode != null && !roomCode.isEmpty()) {
                        String updateRoomSql = "UPDATE rooms SET status = 'available' WHERE room_code = ?";
                        try (PreparedStatement roomPs = conn.prepareStatement(updateRoomSql)) {
                            roomPs.setString(1, roomCode);
                            roomPs.executeUpdate();
                        }
                    }
                }
            }
        }
    }
}